#include "mainwindow.h"
#include <QApplication>
#include <QStyleFactory>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QIntValidator>
#include <QDoubleValidator>
#include <QRegularExpressionValidator>
#include <algorithm>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , centralWidget(nullptr)
    , tabWidget(nullptr)
    , inputTab(nullptr)
    , variableSpinBox(nullptr)
    , inputScrollArea(nullptr)
    , inputGridWidget(nullptr)
    , inputGridLayout(nullptr)
    , equationDisplay(nullptr)
    , solveButton(nullptr)
    , clearButton(nullptr)
    , exampleButton(nullptr)
    , progressBar(nullptr)
    , resultTab(nullptr)
    , resultTextEdit(nullptr)
    , solveTimer(nullptr)
{
    setupUI();
    onVariableCountChanged(3);

    solveTimer = new QTimer(this);
    solveTimer->setSingleShot(true);
}

MainWindow::~MainWindow()
{
    safeDeleteInputs();
}

void MainWindow::safeDeleteInputs()
{
    for (QLineEdit* input : coefficientInputs) {
        if (input) {
            input->deleteLater();
        }
    }
    coefficientInputs.clear();
}

void MainWindow::setupUI()
{
    centralWidget = new QWidget(this);
    setCentralWidget(centralWidget);

    QVBoxLayout *mainLayout = new QVBoxLayout(centralWidget);
    mainLayout->setSpacing(12);
    mainLayout->setContentsMargins(20, 20, 20, 20);

    // 标题栏
    QLabel *titleLabel = new QLabel("Linear Equation System Solver");
    titleLabel->setStyleSheet(
        "font-size: 24px; "
        "font-weight: bold; "
        "color: #1976D2; "
        "padding: 10px; "
        "background: qlineargradient(x1:0, y1:0, x2:1, y2:0, "
        "stop:0 #E3F2FD, stop:1 #BBDEFB); "
        "border-radius: 8px;"
    );
    titleLabel->setAlignment(Qt::AlignCenter);
    mainLayout->addWidget(titleLabel);

    // 选项卡
    tabWidget = new QTabWidget(this);
    tabWidget->setStyleSheet(
        "QTabWidget::pane { "
        "    border: 1px solid #E0E0E0; "
        "    border-radius: 6px; "
        "    background: white; "
        "    padding: 10px; "
        "} "
        "QTabBar::tab { "
        "    background: #F5F5F5; "
        "    border: 1px solid #E0E0E0; "
        "    padding: 10px 20px; "
        "    margin-right: 4px; "
        "    border-top-left-radius: 6px; "
        "    border-top-right-radius: 6px; "
        "    font-weight: 600; "
        "} "
        "QTabBar::tab:selected { "
        "    background: white; "
        "    border-bottom-color: white; "
        "    color: #1976D2; "
        "} "
        "QTabBar::tab:hover { "
        "    background: #E8F4F8; "
        "}"
    );
    mainLayout->addWidget(tabWidget);

    // === 输入选项卡 ===
    inputTab = new QWidget();
    tabWidget->addTab(inputTab, "📊 Input Equations");

    QVBoxLayout *inputTabLayout = new QVBoxLayout(inputTab);
    inputTabLayout->setSpacing(16);
    inputTabLayout->setContentsMargins(15, 15, 15, 15);

    // 控制面板
    QGroupBox *controlGroup = new QGroupBox("⚙️ System Configuration");
    controlGroup->setStyleSheet(
        "QGroupBox { "
        "    font-size: 14px; "
        "    font-weight: bold; "
        "    color: #424242; "
        "    border: 2px solid #E0E0E0; "
        "    border-radius: 8px; "
        "    margin-top: 12px; "
        "    padding-top: 15px; "
        "    background: #FAFAFA; "
        "} "
        "QGroupBox::title { "
        "    subcontrol-origin: margin; "
        "    left: 15px; "
        "    padding: 0 8px; "
        "}"
    );
    QVBoxLayout *controlMainLayout = new QVBoxLayout(controlGroup);
    controlMainLayout->setContentsMargins(15, 10, 15, 10);

    QHBoxLayout *controlLayout = new QHBoxLayout();

    QLabel *variableLabel = new QLabel("Number of variables:");
    variableLabel->setStyleSheet("font-weight: 600; color: #424242; font-size: 13px;");

    variableSpinBox = new QSpinBox();
    variableSpinBox->setRange(1, 8);
    variableSpinBox->setValue(3);
    variableSpinBox->setStyleSheet(
        "QSpinBox { "
        "    padding: 8px 12px; "
        "    border: 2px solid #BDBDBD; "
        "    border-radius: 6px; "
        "    background: white; "
        "    font-size: 13px; "
        "    min-width: 80px; "
        "} "
        "QSpinBox:focus { "
        "    border-color: #1976D2; "
        "}"
    );

    controlLayout->addWidget(variableLabel);
    controlLayout->addWidget(variableSpinBox);
    controlLayout->addStretch();

    controlMainLayout->addLayout(controlLayout);

    // 添加输入格式提示
    QLabel *formatHint = new QLabel("💡 Input formats supported: integers (5), decimals (1.25), fractions (1/2)");
    formatHint->setStyleSheet(
        "font-size: 11px; "
        "color: #757575; "
        "font-weight: normal; "
        "padding: 5px; "
        "background: #E8F5E9; "
        "border-radius: 4px; "
        "margin-top: 5px;"
    );
    formatHint->setWordWrap(true);
    controlMainLayout->addWidget(formatHint);

    inputTabLayout->addWidget(controlGroup);

    // 输入矩阵区域
    QGroupBox *matrixGroup = new QGroupBox("🔢 Coefficient Matrix and Constants");
    matrixGroup->setStyleSheet(
        "QGroupBox { "
        "    font-size: 14px; "
        "    font-weight: bold; "
        "    color: #424242; "
        "    border: 2px solid #E0E0E0; "
        "    border-radius: 8px; "
        "    margin-top: 12px; "
        "    padding-top: 15px; "
        "    background: #FAFAFA; "
        "} "
        "QGroupBox::title { "
        "    subcontrol-origin: margin; "
        "    left: 15px; "
        "    padding: 0 8px; "
        "}"
    );
    QVBoxLayout *matrixLayout = new QVBoxLayout(matrixGroup);
    matrixLayout->setContentsMargins(15, 10, 15, 15);

    inputScrollArea = new QScrollArea();
    inputScrollArea->setWidgetResizable(true);
    inputScrollArea->setMinimumHeight(250);
    inputScrollArea->setStyleSheet(
        "QScrollArea { "
        "    border: 1px solid #E0E0E0; "
        "    border-radius: 6px; "
        "    background: white; "
        "}"
    );

    inputGridWidget = new QWidget();
    inputGridLayout = new QGridLayout(inputGridWidget);
    inputGridLayout->setSpacing(10);
    inputGridLayout->setContentsMargins(15, 15, 15, 15);

    inputScrollArea->setWidget(inputGridWidget);
    matrixLayout->addWidget(inputScrollArea);

    inputTabLayout->addWidget(matrixGroup);

    // 方程预览
    QGroupBox *displayGroup = new QGroupBox("👁️ Equation Preview");
    displayGroup->setStyleSheet(
        "QGroupBox { "
        "    font-size: 14px; "
        "    font-weight: bold; "
        "    color: #424242; "
        "    border: 2px solid #E0E0E0; "
        "    border-radius: 8px; "
        "    margin-top: 12px; "
        "    padding-top: 15px; "
        "    background: #FAFAFA; "
        "} "
        "QGroupBox::title { "
        "    subcontrol-origin: margin; "
        "    left: 15px; "
        "    padding: 0 8px; "
        "}"
    );
    QVBoxLayout *displayLayout = new QVBoxLayout(displayGroup);
    displayLayout->setContentsMargins(15, 10, 15, 15);

    equationDisplay = new QTextEdit();
    equationDisplay->setMaximumHeight(120);
    equationDisplay->setReadOnly(true);
    equationDisplay->setStyleSheet(
        "QTextEdit { "
        "    border: 1px solid #E0E0E0; "
        "    border-radius: 6px; "
        "    padding: 10px; "
        "    background: #FAFAFA; "
        "    font-family: 'Consolas', 'Monaco', monospace; "
        "    font-size: 12px; "
        "    color: #424242; "
        "}"
    );
    displayLayout->addWidget(equationDisplay);

    inputTabLayout->addWidget(displayGroup);

    // 按钮区域
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    buttonLayout->setSpacing(12);

    solveButton = new QPushButton("🚀 Solve System");
    solveButton->setStyleSheet(
        "QPushButton { "
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
        "    stop:0 #4CAF50, stop:1 #45A049); "
        "    border: none; "
        "    color: white; "
        "    padding: 12px 24px; "
        "    border-radius: 6px; "
        "    font-weight: bold; "
        "    font-size: 13px; "
        "    min-width: 140px; "
        "} "
        "QPushButton:hover { "
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
        "    stop:0 #45A049, stop:1 #3D8B40); "
        "} "
        "QPushButton:pressed { "
        "    background: #388E3C; "
        "} "
        "QPushButton:disabled { "
        "    background: #BDBDBD; "
        "}"
    );

    clearButton = new QPushButton("🗑️ Clear All");
    clearButton->setStyleSheet(
        "QPushButton { "
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
        "    stop:0 #F44336, stop:1 #E53935); "
        "    border: none; "
        "    color: white; "
        "    padding: 12px 24px; "
        "    border-radius: 6px; "
        "    font-weight: bold; "
        "    font-size: 13px; "
        "    min-width: 140px; "
        "} "
        "QPushButton:hover { "
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
        "    stop:0 #E53935, stop:1 #C62828); "
        "} "
        "QPushButton:pressed { "
        "    background: #C62828; "
        "}"
    );

    exampleButton = new QPushButton("📚 Load Example");
    exampleButton->setStyleSheet(
        "QPushButton { "
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
        "    stop:0 #2196F3, stop:1 #1976D2); "
        "    border: none; "
        "    color: white; "
        "    padding: 12px 24px; "
        "    border-radius: 6px; "
        "    font-weight: bold; "
        "    font-size: 13px; "
        "    min-width: 140px; "
        "} "
        "QPushButton:hover { "
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
        "    stop:0 #1976D2, stop:1 #1565C0); "
        "} "
        "QPushButton:pressed { "
        "    background: #1565C0; "
        "}"
    );

    buttonLayout->addWidget(solveButton);
    buttonLayout->addWidget(clearButton);
    buttonLayout->addWidget(exampleButton);
    buttonLayout->addStretch();

    inputTabLayout->addLayout(buttonLayout);

    // 进度条
    progressBar = new QProgressBar();
    progressBar->setVisible(false);
    progressBar->setRange(0, 0);
    progressBar->setTextVisible(false);
    progressBar->setStyleSheet(
        "QProgressBar { "
        "    border: 1px solid #E0E0E0; "
        "    border-radius: 6px; "
        "    background: #F5F5F5; "
        "    height: 8px; "
        "} "
        "QProgressBar::chunk { "
        "    background: qlineargradient(x1:0, y1:0, x2:1, y2:0, "
        "    stop:0 #4CAF50, stop:1 #8BC34A); "
        "    border-radius: 6px; "
        "}"
    );
    inputTabLayout->addWidget(progressBar);

    // === 结果选项卡 ===
    resultTab = new QWidget();
    tabWidget->addTab(resultTab, "📈 Results");

    QVBoxLayout *resultLayout = new QVBoxLayout(resultTab);
    resultLayout->setContentsMargins(15, 15, 15, 15);
    resultLayout->setSpacing(12);

    QLabel *resultLabel = new QLabel("✨ Solution and Verification");
    resultLabel->setStyleSheet(
        "font-size: 18px; "
        "font-weight: bold; "
        "color: #1976D2; "
        "padding: 8px; "
        "background: #E3F2FD; "
        "border-radius: 6px;"
    );
    resultLayout->addWidget(resultLabel);

    resultTextEdit = new QTextEdit();
    resultTextEdit->setReadOnly(true);
    resultTextEdit->setStyleSheet(
        "QTextEdit { "
        "    border: 2px solid #E0E0E0; "
        "    border-radius: 8px; "
        "    padding: 15px; "
        "    background: white; "
        "    font-family: 'Consolas', 'Monaco', monospace; "
        "    font-size: 13px; "
        "    color: #212121; "
        "    line-height: 1.6; "
        "}"
    );
    resultLayout->addWidget(resultTextEdit);

    // 连接信号和槽
    connect(variableSpinBox, QOverload<int>::of(&QSpinBox::valueChanged),
            this, &MainWindow::onVariableCountChanged);
    connect(solveButton, &QPushButton::clicked,
            this, &MainWindow::onSolveClicked);
    connect(clearButton, &QPushButton::clicked,
            this, &MainWindow::onClearClicked);
    connect(exampleButton, &QPushButton::clicked,
            this, &MainWindow::onLoadExampleClicked);
    connect(solveTimer, &QTimer::timeout, this, [this]() {
        progressBar->setVisible(false);
        solveButton->setEnabled(true);
    });

    // 设置窗口属性
    setWindowTitle("Linear Equation System Solver");
    setMinimumSize(950, 700);

    // 默认全屏显示
    showMaximized();

    // 全局样式
    setStyleSheet(
        "QMainWindow { "
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
        "    stop:0 #FAFAFA, stop:1 #F5F5F5); "
        "} "
        "QLineEdit { "
        "    padding: 8px; "
        "    border: 2px solid #BDBDBD; "
        "    border-radius: 5px; "
        "    background: white; "
        "    min-width: 60px; "
        "    max-width: 80px; "
        "    font-size: 12px; "
        "    font-weight: 500; "
        "} "
        "QLineEdit:focus { "
        "    border-color: #1976D2; "
        "    background: #E3F2FD; "
        "} "
        "QLineEdit:hover { "
        "    border-color: #757575; "
        "}"
    );
}

void MainWindow::onVariableCountChanged(int value)
{
    createInputGrid(value);
    updateEquationDisplay();
}

void MainWindow::createInputGrid(int n)
{
    safeDeleteInputs();

    QLayoutItem* item;
    while ((item = inputGridLayout->takeAt(0)) != nullptr) {
        if (item->widget()) {
            item->widget()->deleteLater();
        }
        delete item;
    }

    // 创建表头
    QLabel *headerLabel = new QLabel("Equation");
    headerLabel->setStyleSheet(
        "font-weight: bold; "
        "color: #1976D2; "
        "font-size: 13px; "
        "padding: 5px;"
    );
    inputGridLayout->addWidget(headerLabel, 0, 0);

    for (int j = 0; j < n; j++) {
        QLabel *varLabel = new QLabel(QString("x%1").arg(j + 1));
        varLabel->setStyleSheet(
            "font-weight: bold; "
            "color: #1976D2; "
            "font-size: 13px; "
            "padding: 5px;"
        );
        varLabel->setAlignment(Qt::AlignCenter);
        inputGridLayout->addWidget(varLabel, 0, j + 1);
    }

    QLabel *constLabel = new QLabel("Constant");
    constLabel->setStyleSheet(
        "font-weight: bold; "
        "color: #F57C00; "
        "font-size: 13px; "
        "padding: 5px;"
    );
    constLabel->setAlignment(Qt::AlignCenter);
    inputGridLayout->addWidget(constLabel, 0, n + 1);

    // 创建输入框
    for (int i = 0; i < n; i++) {
        QLabel *eqLabel = new QLabel(QString("Eq %1").arg(i + 1));
        eqLabel->setStyleSheet(
            "font-weight: 600; "
            "color: #424242; "
            "font-size: 12px; "
            "padding: 5px;"
        );
        inputGridLayout->addWidget(eqLabel, i + 1, 0);

        for (int j = 0; j < n; j++) {
            QLineEdit *input = new QLineEdit();
            input->setPlaceholderText("0");
            input->setAlignment(Qt::AlignCenter);
            input->installEventFilter(this);
            inputGridLayout->addWidget(input, i + 1, j + 1);
            coefficientInputs.push_back(input);

            connect(input, &QLineEdit::textChanged, this, &MainWindow::onInputChanged);
        }

        QLineEdit *constInput = new QLineEdit();
        constInput->setPlaceholderText("0");
        constInput->setAlignment(Qt::AlignCenter);
        constInput->installEventFilter(this);
        constInput->setStyleSheet(
            "QLineEdit { "
            "    padding: 8px; "
            "    border: 2px solid #FF9800; "
            "    border-radius: 5px; "
            "    background: white; "
            "    min-width: 60px; "
            "    max-width: 80px; "
            "    font-size: 12px; "
            "    font-weight: 500; "
            "} "
            "QLineEdit:focus { "
            "    border-color: #F57C00; "
            "    background: #FFF3E0; "
            "}"
        );
        inputGridLayout->addWidget(constInput, i + 1, n + 1);
        coefficientInputs.push_back(constInput);

        connect(constInput, &QLineEdit::textChanged, this, &MainWindow::onInputChanged);
    }
}

bool MainWindow::validateInput(const QString& input)
{
    if (input.isEmpty()) return true;

    QString trimmed = input.trimmed();

    // 检查空字符串
    if (trimmed.isEmpty()) return true;

    // 检查是否为纯数字（整数或小数）
    bool isNumber;
    trimmed.toDouble(&isNumber);
    if (isNumber) return true;

    // 检查分数格式
    if (trimmed.contains('/')) {
        QStringList parts = trimmed.split('/');
        if (parts.size() != 2) return false;

        bool numOk, denOk;
        parts[0].toDouble(&numOk);
        parts[1].toDouble(&denOk);

        return numOk && denOk && parts[1].toDouble() != 0;
    }

    return false;
}

void MainWindow::onInputChanged()
{
    // 验证输入格式
    QLineEdit* senderEdit = qobject_cast<QLineEdit*>(sender());
    if (senderEdit) {
        QString text = senderEdit->text();
        if (!validateInput(text) && !text.isEmpty()) {
            senderEdit->setStyleSheet(
                "QLineEdit { "
                "    padding: 8px; "
                "    border: 2px solid #F44336; "
                "    border-radius: 5px; "
                "    background: #FFEBEE; "
                "    min-width: 60px; "
                "    max-width: 80px; "
                "    font-size: 12px; "
                "    font-weight: 500; "
                "}"
            );
        } else {
            // 恢复默认样式
            if (senderEdit->styleSheet().contains("FF9800")) { // 常数输入框
                senderEdit->setStyleSheet(
                    "QLineEdit { "
                    "    padding: 8px; "
                    "    border: 2px solid #FF9800; "
                    "    border-radius: 5px; "
                    "    background: white; "
                    "    min-width: 60px; "
                    "    max-width: 80px; "
                    "    font-size: 12px; "
                    "    font-weight: 500; "
                    "} "
                    "QLineEdit:focus { "
                    "    border-color: #F57C00; "
                    "    background: #FFF3E0; "
                    "}"
                );
            } else {
                senderEdit->setStyleSheet(""); // 使用全局样式
            }
        }
    }

    updateEquationDisplay();
}

void MainWindow::updateEquationDisplay()
{
    int n = variableSpinBox->value();
    QStringList equations;

    for (int i = 0; i < n; i++) {
        QString equation = QString("Equation %1: ").arg(i + 1);
        bool firstTerm = true;

        for (int j = 0; j < n; j++) {
            QLineEdit *input = coefficientInputs[i * (n + 1) + j];
            QString text = input->text();

            if (!text.isEmpty() && validateInput(text)) {
                try {
                    Fraction f(text.toStdString());
                    double value = f.toDouble();

                    if (std::abs(value) > 1e-10) { // 非零系数
                        QString sign = "";
                        if (!firstTerm) {
                            sign = value >= 0 ? " + " : " - ";
                        } else if (value < 0) {
                            sign = "-";
                        }

                        QString coeff = "";
                        if (std::abs(std::abs(value) - 1.0) > 1e-10) {
                            // 如果系数不是1或-1，显示系数
                            if (f.getDenominator() == 1) {
                                coeff = QString::number(std::abs(value));
                            } else {
                                coeff = f.toString().c_str();
                                if (coeff.startsWith("-")) coeff = coeff.mid(1);
                            }
                            coeff += "·";
                        }
                        equation += QString("%1%2x%3").arg(sign).arg(coeff).arg(j + 1);
                        firstTerm = false;
                    }
                } catch (...) {
                    // 忽略解析错误，在输入验证中已经处理
                }
            }
        }

        QLineEdit *constInput = coefficientInputs[i * (n + 1) + n];
        QString constText = constInput->text();
        if (!constText.isEmpty() && validateInput(constText)) {
            try {
                Fraction f(constText.toStdString());
                equation += QString(" = %1").arg(f.toString().c_str());
            } catch (...) {
                equation += " = ?";
            }
        } else if (firstTerm) {
            equation += "0 = 0";
        } else {
            equation += " = 0";
        }

        equations.append(equation);
    }

    equationDisplay->setPlainText(equations.join("\n"));
}

void MainWindow::onSolveClicked()
{
    int n = variableSpinBox->value();
    std::vector<std::string> inputs;

    bool allValid = true;
    for (QLineEdit* input : coefficientInputs) {
        if (input->text().isEmpty()) {
            allValid = false;
            break;
        }
    }

    if (!allValid) {
        QMessageBox::warning(this, "⚠️ Input Error",
                           "Please fill all coefficients and constants.");
        return;
    }

    // 验证所有输入格式
    for (QLineEdit* input : coefficientInputs) {
        QString text = input->text();
        if (!validateInput(text)) {
            QMessageBox::warning(this, "⚠️ Input Error",
                               QString("Invalid input format: %1\n\nSupported formats: integers (5), decimals (1.25), fractions (1/2)").arg(text));
            return;
        }
    }

    for (QLineEdit* input : coefficientInputs) {
        inputs.push_back(input->text().toStdString());
    }

    progressBar->setVisible(true);
    solveButton->setEnabled(false);

    QTimer::singleShot(100, [this, n, inputs]() {
        try {
            std::string result = solver.solveEquations(n, inputs);
            showResult(QString::fromStdString(result));
        }
        catch (const std::exception& e) {
            showError(QString("Solution Error: %1").arg(e.what()));
        }

        progressBar->setVisible(false);
        solveButton->setEnabled(true);
        tabWidget->setCurrentIndex(1);
    });
}

void MainWindow::onClearClicked()
{
    for (QLineEdit* input : coefficientInputs) {
        input->clear();
    }
    resultTextEdit->clear();
    updateEquationDisplay();
}

void MainWindow::onLoadExampleClicked()
{
    loadExampleSystem();
}

void MainWindow::loadExampleSystem()
{
    variableSpinBox->setValue(3);

    QTimer::singleShot(100, [this]() {
        // 使用一个已知正确的简单示例
        QStringList exampleValues = {
            "2", "1", "1", "8",
            "1", "2", "1", "10",
            "1", "1", "2", "9"
        };

        for (int i = 0; i < coefficientInputs.size() && i < exampleValues.size(); i++) {
            coefficientInputs[i]->setText(exampleValues[i]);
        }

        updateEquationDisplay();

        QMessageBox::information(this, "✅ Example Loaded",
            "A simple 3×3 example system has been loaded.\n\n"
            "Equation: 2x + y + z = 8\n"
            "Equation: x + 2y + z = 10\n"
            "Equation: x + y + 2z = 9\n\n"
            "Solution should be: x=2, y=3, z=2\n\n"
            "Click 'Solve System' to verify!");
    });
}

void MainWindow::showResult(const QString& result)
{
    resultTextEdit->setPlainText(result);
}

void MainWindow::showError(const QString& error)
{
    resultTextEdit->setPlainText("❌ ERROR: " + error);
}

bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
    if (event->type() == QEvent::Wheel) {
        QLineEdit *lineEdit = qobject_cast<QLineEdit*>(obj);
        if (lineEdit && lineEdit->hasFocus()) {
            QWheelEvent *wheelEvent = static_cast<QWheelEvent*>(event);

            // 获取当前值
            QString currentText = lineEdit->text();
            double currentValue = 0;

            if (!currentText.isEmpty() && validateInput(currentText)) {
                try {
                    Fraction f(currentText.toStdString());
                    currentValue = f.toDouble();
                } catch (...) {
                    // 如果解析失败，使用0
                    currentValue = 0;
                }
            }

            // 根据滚轮方向调整值
            int delta = wheelEvent->angleDelta().y();
            double step = 0.1;

            // 按住Ctrl键时步长为1
            if (wheelEvent->modifiers() & Qt::ControlModifier) {
                step = 1.0;
            }
            // 按住Shift键时步长为5
            else if (wheelEvent->modifiers() & Qt::ShiftModifier) {
                step = 5.0;
            }

            if (delta > 0) {
                currentValue += step;
            } else if (delta < 0) {
                currentValue -= step;
            }

            // 设置新值（保持为整数如果可能，否则保留小数）
            if (std::abs(currentValue - std::round(currentValue)) < 1e-10) {
                lineEdit->setText(QString::number(static_cast<int>(std::round(currentValue))));
            } else {
                lineEdit->setText(QString::number(currentValue, 'f', 2));
            }

            return true; // 事件已处理
        }
    }

    return QMainWindow::eventFilter(obj, event);
}
